import Stomp from 'stompjs'

class StompJs {
  client = null
  static instance = null
  config = {}
  isConnect = false

  constructor() {
    if (StompJs.instance) {
      return StompJs.instance
    }
    this.config = {
      url: process.env.stompUrl,
      user: process.env.stompUser,
      password: process.env.stompPwd
    }
    StompJs.instance = this
  }

  getClient() {
    return new Promise((resolve, reject) => {
      if (!this.client) {
        this.client = Stomp.client(this.config.url)
        this.client.connect(this.config.user, this.config.password, () => {
          resolve(this.client)
        }, (error) => {
          reject(error)
        }, 'athena')
      } else {
        return resolve(this.client)
      }
    })
  }

  /**
   * 订阅
   * @param url string 订阅地址
   * @param cb 回调函数
   */
  subscribe(url, cb = (message) => {
  }) {
    return this.getClient().then(client => {
      return client.subscribe(url, cb)
    })
  }

  /**
   * 发消息
   * @param url string 订阅地址
   * @param body string 发送的消息
   * @param headers json 额外的header消息
   */
  send(url, body, headers = {}) {
    this.getClient().then(client => {
      client.send(url, headers, body)
    })
  }

  /**
   * 断开消息
   * @param cb function 回调方法
   */
  disconnect(cb = () => {
  }) {
    if (this.client) {
      this.client.disconnect(cb)
    } else {
      cb()
    }
  }
}

export default StompJs
